package com.pentalog.webservice;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import org.springframework.ws.soap.SoapHeader;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.pentalog.bo.BookBo;
import com.pentalog.domain.Book;
import com.pentalog.domain.BookRequest;
import com.pentalog.domain.BookResponse;
import com.pentalog.exception.BookException;

@Endpoint
public class BookEndPoint {
	
	@Autowired
	private BookBo bookBo;

    private static final String NAMESPACE = "http://localhost:8080/SoapSpring/soap";
    
	public void setBookBo(BookBo bookBo) {
		this.bookBo = bookBo;
	}
	
	

	public BookEndPoint() {
		super();
		// TODO Auto-generated constructor stub
	}



	@PayloadRoot(localPart = "processOrder", namespace = NAMESPACE)
    @ResponsePayload
    public Element processOrder(@RequestPayload Element request) throws ParserConfigurationException {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Element response = document.createElementNS(NAMESPACE, "bookResponse");
        String code = getElementText(request);
        Book book = bookBo.getBookByCode(code);
        response.appendChild(addElementWithValue(document, "itemCode", book.getItemCode()));
        response.appendChild(addElementWithValue(document, "bookName", book.getBookName()));
        response.appendChild(addElementWithValue(document, "Author", book.getAuthor()));
        return response;
    }
	
	@PayloadRoot(localPart = "bookRequest", namespace = NAMESPACE)
    @ResponsePayload
    public BookResponse processOrder1(@RequestPayload BookRequest request, SoapHeader header) throws ParserConfigurationException, BookException {
        BookResponse response = bookBo.getBookResponseByCode(request.getItemCode());
		return response;
    }
	
	public String getElementText(Element element) {
	      StringBuffer buffer = new StringBuffer();
	      NodeList nodeList = element.getChildNodes();
	      for (int i = 0; i < nodeList.getLength(); i++) {
	          Node node = nodeList.item(i);
	          if (node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.CDATA_SECTION_NODE) {
	              buffer.append(node.getNodeValue());
	          }
	      }
	      return buffer.toString();
	  }
    
    private Element addElementWithValue(Document document, String element, String value){
        Element child = document.createElementNS(NAMESPACE, element);
        child.appendChild(document.createTextNode(value));
        return child;
    }
}
